import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:flutter_application_1/route/router.dart';
import 'package:flutter_application_1/pages/home/home_vm.dart';
import 'package:flutter_application_1/models/home_article_data.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    viewModel.getBanner();
    viewModel.initArticleList(false);
  }

  listAdd() {
    viewModel.initArticleList(true);
    refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>(
        create: (context) => viewModel,
        child: Scaffold(
            body: SafeArea(
          child: SmartRefresher(
              controller: refreshController,
              enablePullUp: true,
              enablePullDown: true,
              header: const ClassicHeader(),
              footer: const ClassicFooter(),
              onLoading: () {
                // 上拉
                listAdd();
              },
              onRefresh: () {
                // 下拉
                viewModel.getBanner();
                viewModel.initArticleList(false);
                refreshController.refreshCompleted();
              },
              child: SingleChildScrollView(
                child: Column(children: [
                  _bannerView(),
                  _articleView(),
                ]),
              )),
        )));
  }

  Widget _bannerView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return Container(
        height: 200,
        width: double.infinity,
        child: Swiper(
          indicatorLayout: PageIndicatorLayout.NONE,
          control: const SwiperControl(),
          pagination: const SwiperPagination(),
          autoplay: true,
          itemBuilder: (context, index) {
            return Container(
              width: double.infinity,
              height: 150,
              color: Colors.red,
              child: Image.network(
                vm.bannerList?[index].imagePath ?? '',
                fit: BoxFit.cover,
              ),
            );
          },
          itemCount: vm.bannerList?.length ?? 0,
        ),
      );
    });
  }

  Widget _articleView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return _listItemView(vm.articleList[index]);
        },
        itemCount: vm.articleList.length,
      );
    });
  }

  Widget _listItemView(Datas item) {
    String name;
    if (item.author?.isNotEmpty ?? false) {
      name = item.author ?? "";
    } else {
      name = item.shareUser ?? "";
    }
    return GestureDetector(
        onTap: () {
          Navigator.pushNamed(context, RouterPath.webview,
              arguments: {"title": "使用路由传参"});
        },
        child: Container(
          margin: const EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
          padding:
              const EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            border: Border.all(color: Colors.black, width: 0),
            color: Colors.white,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: Image.network(
                      "https://q9.itc.cn/q_70/images03/20241013/d770472d4906402c866b9c71a0c9927c.jpeg",
                      width: 40,
                      height: 40,
                    ),
                  ),
                  const Padding(padding: EdgeInsets.only(left: 6)),
                  Text(
                    name,
                    style: TextStyle(fontSize: 14),
                  ),
                  const Expanded(child: SizedBox()),
                  Text(
                    item?.niceShareDate ?? "",
                    style: TextStyle(fontSize: 12, color: Color(0xff666666)),
                  ),
                  const Padding(padding: EdgeInsets.only(right: 6)),
                  if (item.type == 1)
                    const Text(
                      '置顶',
                      style: TextStyle(color: Colors.red),
                    ),
                ],
              ),
              const SizedBox(
                height: 6,
              ),
              Text(
                item?.title ?? "",
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
              ),
              Row(
                children: [
                  Text(
                    item?.chapterName ?? "",
                    style: TextStyle(color: Colors.blue),
                  ),
                  const Expanded(child: SizedBox()),
                  Image.asset(
                    'assets/images/collect.png',
                    width: 24,
                    height: 24,
                  ),
                ],
              )
            ],
          ),
        ));
  }
}
